package database

import (
	"GOPAAS/configs/config"
	"GOPAAS/internal/app/global"
	"gorm.io/gorm"
)

var DriverMap = make(map[string]*gorm.DB, 10)

func InitDriver(config config.DbConfigs) {
	for k, v := range config {
		if v.Type == "postgresql" {
			DriverMap[k] = connectPostGre(v)
		} else if v.Type == "mysql" {
			DriverMap[k] = connectMysql(v)
		}
	}
}

func GetInstance(name string) *gorm.DB {
	//不需要重新加载
	if !global.ReloadDatabase {
		if driver, ok := DriverMap[name]; ok {
			return driver
		}
	}
	conf := config.Conf.Database[name]
	if conf.Type == "postgresql" {
		DriverMap[name] = connectPostGre(conf)
	} else if conf.Type == "mysql" {
		DriverMap[name] = connectMysql(conf)
	}
	global.ReloadDatabase = false
	return DriverMap[name]
}
